package com.andnux.android.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.andnux.android.MainApp;
import com.andnux.android.adapter.OnItemClickListener;
import com.andnux.android.adapter.PhotoAdapter;
import com.andnux.android.data.Orders;
import com.andnux.android.data.OrdersComment;
import com.andnux.android.data.SystemUsers;
import com.andnux.android.databinding.ActivityCommentBinding;
import com.andnux.android.databinding.ItemImageBinding;
import com.andnux.android.network.DesignCloudApi;
import com.andnux.android.network.GsonUtils;
import com.andnux.android.network.NotNullConsumer;
import com.andnux.android.network.Result;
import com.andnux.android.network.RetrofitClient;
import com.andnux.android.network.SuccessConsumer;
import com.andnux.android.utils.GlideEngine;
import com.andnux.android.utils.ImageLoader;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class CommentActivity extends BaseActivity<ActivityCommentBinding> {

    private Orders orders;
    private final List<String> photos = new ArrayList<>();
    private PhotoAdapter adapter;
    private DesignCloudApi api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = RetrofitClient.getInstance().getServerApi();
        orders = (Orders) getIntent().getSerializableExtra("orders");
        binding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        String json = orders.getWorks().getFiles();
        List<String> files = GsonUtils.gson.fromJson(json, new TypeToken<List<String>>() {
        }.getType());
        ImageLoader.load(files.get(0), binding.worksImage);
        binding.worksTitle.setText(orders.getWorks().getTitle());
        binding.worksPrice.setText(orders.getPrice());
        binding.allPrice1.setText(orders.getPrice());

        adapter = new PhotoAdapter();
        photos.add("-");
        adapter.setOnItemClickListener(new OnItemClickListener<ItemImageBinding>() {
            @Override
            public void onItemClick(ItemImageBinding view, int position, long id) {
                if (position == photos.size() - 1) {
                    PictureSelector.create(CommentActivity.this)
                            .openGallery(SelectMimeType.ofAll())
                            .setMaxSelectNum(6)
                            .setImageEngine(GlideEngine.createGlideEngine())
                            .forResult(new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(ArrayList<LocalMedia> result) {
                                    uploadFiles(result);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });

                } else {

                }
            }
        });
        binding.content.setAdapter(adapter);
        adapter.setNewData(photos);

        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = binding.text.getText().toString();
                if (TextUtils.isEmpty(text) || photos.size() <= 1) {
                    Toast.makeText(CommentActivity.this, "请添加描述和图片", Toast.LENGTH_SHORT).show();
                    return;
                }
                SystemUsers users = MainApp.getApp().getSystemUsers();
                OrdersComment comment = new OrdersComment();
                comment.setContent(text);
                comment.setCreateTime(new Date());
                comment.setOrderId(String.valueOf(orders.getId()));
                comment.setServiceScore(5);
                comment.setTimeScore(5);
                comment.setUserId(String.valueOf(users.getId()));
                comment.setWorksId(orders.getWorksId());
                comment.setDeleted("0");
                comment.setIsShow(1);
                List<String> list = new ArrayList<>();
                for (String photo : photos) {
                    if (!photo.equalsIgnoreCase("-")) {
                        list.add(photo);
                    }
                }
                comment.setImages(GsonUtils.gson.toJson(list));
                addDisposable(api.orderCommentInsert(comment)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SuccessConsumer<Result<OrdersComment>>() {
                            @Override
                            public void onSuccess(Result<OrdersComment> result) {
                                orders.setStatus(4);
                                orderUpdate(orders);
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                if (throwable != null) {
                                    Toast.makeText(CommentActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        }));
            }
        });
    }

    private void orderUpdate(Orders vo) {
        addDisposable(api.orderUpdate(vo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SuccessConsumer<Result<Orders>>() {
                    @Override
                    public void onSuccess(Result<Orders> result) {
                        Toast.makeText(CommentActivity.this, "评论成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        if (throwable != null) {
                            Toast.makeText(CommentActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));
    }


    @Override
    protected void onDestroy() {
        adapter.stop();
        super.onDestroy();
    }


    private void uploadFiles(ArrayList<LocalMedia> result) {
        DesignCloudApi api = RetrofitClient.getInstance().getServerApi();
        for (LocalMedia s : result) {
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);
            File file = new File(s.getRealPath());
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("file", file.getName(), imageBody);
            addDisposable(api.fileUpload(builder.build().parts())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new NotNullConsumer<Result<String>>() {
                        @Override
                        public void onSuccess(Result<String> result) {
                            photos.add(0, result.getData());
                            adapter.setNewData(photos);
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            if (throwable != null) {
                                Toast.makeText(CommentActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }));
        }
    }
}